package com.guochu.sys.controller;


import com.guochu.common.ResultMap;
import com.guochu.utils.MapUtils;
import com.guochu.utils.WxPay.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;


@RestController
@RequestMapping("sys/wxpay")
public class WxPayController {
    public static String APPID = "wx38316ee4df1944cd";
    public static String MCHID = "1614200164";
    public static String PATERNERKEY = "9qWLxO7vJAXE8IQM2L7NuzjyMWAb3Dmn";

    /**
     * 统一下单接口
     *
     * @param limit
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/pay", method = RequestMethod.POST)
    public ResultMap pay(@RequestBody Map<String, Object> limit) throws Exception {
        Map<String, String> payMap = new HashMap<String, String>();
        String openId = MapUtils.getString(limit, "openId"); // 用户的openid
        // 拼接统一下单地址参数
        Map<String, String> paraMap = new HashMap<String, String>();
        paraMap.put("appid", APPID);
        paraMap.put("body", "购买商品");
        paraMap.put("device_info", "WEB");
        paraMap.put("mch_id", MCHID);
        paraMap.put("nonce_str", WXPayUtil.generateNonceStr()); // UUID
        paraMap.put("openid", openId);
        paraMap.put("out_trade_no", getOrderNo());// 订单号,每次都不同
        paraMap.put("spbill_create_ip", "14.23.150.211");
        paraMap.put("total_fee", "1"); // 支付金额，单位分
        paraMap.put("trade_type", "JSAPI"); // 支付类型
        paraMap.put("notify_url", "http://www.ddd.com");// 此路径是微信服务器调用支付结果通知路径随意写
        String sign = WXPayUtil.generateSignature(paraMap, PATERNERKEY);
        paraMap.put("sign", sign);
        String xml = WXPayUtil.mapToXml(paraMap);// 将所有参数(map)转xml格式
        // 统一下单 https://api.mch.weixin.qq.com/pay/unifiedorder
        String unifiedorder_url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        System.out.println("xml为：" + xml);
        String xmlStr = HttpRequest.httpsRequest(unifiedorder_url, "POST", xml);
        // 以下内容是返回前端页面的json数据
        String prepay_id = "";// 预支付id
        if (xmlStr.indexOf("SUCCESS") != -1) {
            Map<String, String> map = WXPayUtil.xmlToMap(xmlStr);
            prepay_id = (String) map.get("prepay_id");
        }
        payMap.put("appId", APPID);
        payMap.put("timeStamp", WXPayUtil.getCurrentTimestamp() + "");
        payMap.put("nonceStr", WXPayUtil.generateNonceStr());
        payMap.put("signType", "MD5");
        payMap.put("package", "prepay_id=" + prepay_id);
        String paySign = WXPayUtil.generateSignature(payMap, PATERNERKEY);
        payMap.put("paySign", paySign);
        //将这个6个参数传给前端
        return ResultMap.success().put("item", payMap);
    }

    /**
     * 获取订单信息
     *
     * @param limit
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getOrderById", method = RequestMethod.POST)
    public ResultMap getOrderById(@RequestBody Map<String, Object> limit) throws Exception {
        MyConfig config = new MyConfig();
        WXPay wxpay = new WXPay(config);
        Map<String, String> data = new HashMap<String, String>();
        data.put("out_trade_no", "20210907205416082");
        Map<String, String> resp = wxpay.orderQuery(data);
        return ResultMap.success().put("item", resp);
    }

    /**
     * 生成订单号
     *
     * @return
     */
    public static String getOrderNo() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate = sdf.format(new Date());
        String result = "";
        Random random = new Random();
        for (int i = 0; i < 3; i++) {
            result += random.nextInt(10);
        }
        return newDate + result;
    }

}